package cn.net.wanji.controller;

import cn.net.wanji.cache.CacheManager;
import cn.net.wanji.domain.AjaxResult;
import cn.net.wanji.entity.*;
import cn.net.wanji.entity.page.BaseController;
import cn.net.wanji.entity.page.TableDataInfo;
import cn.net.wanji.job.RefreshCongestionDataJob;
import cn.net.wanji.service.MonitorService;
import cn.net.wanji.utils.*;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static cn.net.wanji.job.RefreshIndexScheduledTask.jsonObject;


/**
 * 监控数据列表
 *
 * @author weining
 * @date 2023/12/25 10:18
 */

@Slf4j(topic = "查询类")
@RestController
@RequestMapping(value = "/monitor")
public class MonitorController extends BaseController {

    @Autowired
    private MonitorService monitorService;
    @Autowired
    private RefreshCongestionDataJob refreshCongestionDataJob;

    @Autowired
    private CacheManager cacheManager;

    @GetMapping("/data")
    public AjaxResult monitorData(@RequestParam("date") String date) {
        try {
            if (jsonObject != null) {
                return AjaxResult.success(jsonObject);
            } else {
                return AjaxResult.error(JSONObject.toJSONString(jsonObject));
            }
        } catch (Exception e) {
            LogUtils.errorLog(e);
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping("events")
    public TableDataInfo events(EventParam eventParam) {
        long startTime = System.currentTimeMillis();
        startPage();
        List<EventCar> resultList = monitorService.events(eventParam);
        long endTime = System.currentTimeMillis();
        logger.info("events事件接口数据处理时间====》{}", endTime - startTime);
        return getDataTable(resultList);
    }

    @GetMapping("exportEvent")
    public void exportEvent(EventParam eventParam, HttpServletResponse response) {
        // 获取当前时间
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
        String dateTime = dateFormat.format(currentDate);
        String fileName = "事件管理记录表_" + dateTime;
        // 设置响应输出的头类型
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        List<EventCar> resultList = monitorService.events(eventParam);
        ArrayList<EventCarVo> eventCarVos = new ArrayList<>();
        for (EventCar eventCar : resultList) {
            EventCarVo eventCarVo = new EventCarVo();
            eventCarVo.setGantryTime(eventCar.getGantryTime());
            eventCarVo.setPlate(eventCar.getPlate());
            if (StringUtils.isEmpty(eventCar.getType())) {
                eventCarVo.setType("未知");
            } else {
                eventCarVo.setType(IdentifyTypeEnum.getValueByNumber(Integer.parseInt(eventCar.getType())));
            }
            eventCarVo.setEventType(EventTypeEnum.getValueByNumber(Integer.parseInt(eventCar.getEventType())));
            if ("3".equals(eventCar.getEventType())) {
                // 计算滞留
                if (StringUtils.isEmpty(eventCar.getDownBridgeTime())) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    // 解析输入的日期时间字符串
                    LocalDateTime inputDateTime = LocalDateTime.parse(eventCar.getUpBridgeTime(), formatter);
                    // 获取当前日期时间
                    long minutesDifference = 0L;
                    LocalDateTime nowDate = LocalDateTime.now();
                    if (inputDateTime.toLocalDate().isEqual(nowDate.toLocalDate())) {
                        // 格式化当前日期时间为字符串
                        String formattedDateTime = nowDate.format(formatter);
                        minutesDifference = TimeUtils.calculateMinutesDifference(eventCar.getUpBridgeTime(), formattedDateTime);
                    } else {
                        // 解析输入的日期时间字符串
                        LocalDateTime inputNext = LocalDateTime.parse(eventCar.getUpBridgeTime(), formatter);
                        // 获取下一天的日期
                        LocalDateTime nextDayDateTime = inputNext.plusDays(1);
                        // 设置时间为0点
                        LocalDateTime midnightNextDay = LocalDateTime.of(nextDayDateTime.toLocalDate(), LocalDateTime.MIN.toLocalTime());
                        // 格式化结果
                        String formattedResult = midnightNextDay.format(formatter);
                        minutesDifference = TimeUtils.calculateMinutesDifference(eventCar.getUpBridgeTime(), formattedResult);
                    }
                    // 计算当前时间和上桥时间的时间差
                    eventCarVo.setDescribe("滞留了" + minutesDifference + "分钟");
                } else {
                    long minutesDifference = TimeUtils.calculateMinutesDifference(eventCar.getUpBridgeTime(),
                            eventCar.getDownBridgeTime());
                    eventCarVo.setDescribe("滞留了" + minutesDifference + "分钟");
                }
            } else if ("1".equals(eventCar.getEventType()) || "2".equals(eventCar.getEventType())) {
                eventCarVo.setDescribe("速度" + eventCar.getSpeed() + "km/h");
            }
            eventCarVos.add(eventCarVo);
        }
        try {
            ExcelUtils.exportExcel(eventCarVos, "事件管理记录表", "工作表1", EventCarVo.class,
                    fileName, response);
        } catch (IOException e) {
            logger.error("导出事件数据失败");
        }

    }

    @GetMapping("getCrossingData")
    public TableDataInfo getCrossingData(CrossingDataParam crossingDataParam) {
        long startTime = System.currentTimeMillis();
        startPage();
        List<CrossCar> resultList = monitorService.getCrossingData(crossingDataParam);
        long endTime = System.currentTimeMillis();
        logger.info("getCrossingData过车数据接口数据处理时间====》{}", endTime - startTime);
        return getDataTable(resultList);
    }

    @GetMapping("exportCrossingData")
    public void exportCrossingData(CrossingDataParam crossingDataParam, HttpServletResponse response) {
        // 获取当前时间
        Date currentDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
        String dateTime = dateFormat.format(currentDate);
        String fileName = "过车数据记录表_" + dateTime;
        // 设置响应输出的头类型
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        List<CrossCar> resultList = monitorService.getCrossingData(crossingDataParam);
        ArrayList<CrossCarVo> crossCarVos = new ArrayList<>();
        for (CrossCar crossCar : resultList) {
            CrossCarVo crossCarVo = new CrossCarVo();
            crossCarVo.setUpBridgeTime(crossCar.getUpBridgeTime());
            crossCarVo.setDangerousGoods(crossCar.getDangerousGoods());
            crossCarVo.setLicenseCode(crossCar.getLicenseCode());
            if (StringUtils.isEmpty(String.valueOf(crossCar.getIdentifyType()))) {
                crossCarVo.setIdentifyType("未知");
            } else {
                crossCarVo.setIdentifyType(IdentifyTypeEnum.getValueByNumber(Integer.parseInt(String.valueOf(crossCar.getIdentifyType()))));
            }
            if (crossCar.getVehicleSpeed() == null) {
                crossCarVo.setVehicleSpeed("");
            } else {
                crossCarVo.setVehicleSpeed(crossCar.getVehicleSpeed() + "km/h");
            }

            crossCarVo.setDownBridgeTime(crossCar.getDownBridgeTime());
            if (crossCar.getRateNumber() == 0) {
                crossCarVo.setRateNumber(1);
            } else {
                crossCarVo.setRateNumber(crossCar.getRateNumber());
            }
            crossCarVos.add(crossCarVo);
        }
        try {
            ExcelUtils.exportExcel(crossCarVos, "过车数据记录表", "工作表1", CrossCarVo.class,
                    fileName, response);
        } catch (IOException e) {
            logger.error("导出事件数据失败");
        }
    }

    @GetMapping("getCrossingDataAnalysis")
    public AjaxResult getCrossingDataAnalysis(CrossingDataParam crossingDataParam) {
        long startTime = System.currentTimeMillis();
        if (crossingDataParam == null) {
            return AjaxResult.error("开始时间和结束时间不能为空");
        }
        if (StringUtils.isEmpty(crossingDataParam.getStartTime()) || StringUtils.isEmpty(crossingDataParam.getEndTime())) {
            return AjaxResult.error("开始时间和结束时间不能为空");
        }
        JSONObject jsonObject = monitorService.getCrossingDataAnalysis(crossingDataParam);
        long endTime = System.currentTimeMillis();
        logger.info("getCrossingDataAnalysis统计分析数据接口数据处理时间====》{}", endTime - startTime);
        return AjaxResult.success(jsonObject);
    }

    @GetMapping("getAntennaInfo")
    public AjaxResult getAntennaInfo() {
        long startTime = System.currentTimeMillis();
        List<AntennaInfo> antennaInfo = monitorService.getAntennaInfo();
        long endTime = System.currentTimeMillis();
        logger.info("getAntennaInfo获取天线数据接口数据处理时间====》{}", endTime - startTime);
        return AjaxResult.success(antennaInfo);
    }

    @GetMapping("setCache")
    public AjaxResult setCache(String key, String value) throws Exception {
        ArrayList<String> list = new ArrayList<>();
        list.add(value);
        list.add(value);
        list.add(value);
        cacheManager.put(key, list, 10);
        return AjaxResult.success(list);
    }

    /*@GetMapping("getCache")
    public AjaxResult getCache() {
        List<String> list = cacheManager.get(key, String.class);
        return AjaxResult.success(list);
    }*/

    @GetMapping("getCacheByKey")
    public AjaxResult getCache(String key) throws Exception {
        List<String> list = cacheManager.get(key, String.class);
        return AjaxResult.success(list);
    }

    /**
     * 获取拥堵信息
     *
     * @author lizhenwang
     * @date 2023/1/12 08:53
     */
    @GetMapping("getCongestionInfo")
    public AjaxResult getCongestionInfo() {
        CongestionInfo congestionInfo = new CongestionInfo();
        //在0 1 2 3 四个中中随机生成一个数
//        congestionInfo.setRegion1((int) (Math.random() * 4));
//        congestionInfo.setRegion2((int) (Math.random() * 4));
//        congestionInfo.setRegion3((int) (Math.random() * 4));
//        congestionInfo.setRegion4((int) (Math.random() * 4));
//        congestionInfo.setRegion5((int) (Math.random() * 4));
//        congestionInfo.setRegion6((int) (Math.random() * 4));
//        congestionInfo.setRegion7((int) (Math.random() * 4));
        congestionInfo.setRegion1(refreshCongestionDataJob.region1);
        congestionInfo.setRegion2(refreshCongestionDataJob.region2);
        congestionInfo.setRegion3(refreshCongestionDataJob.region3);
        congestionInfo.setRegion4(refreshCongestionDataJob.region4);
        congestionInfo.setRegion5(refreshCongestionDataJob.region5);
        congestionInfo.setRegion6(refreshCongestionDataJob.region6);
        congestionInfo.setRegion7(refreshCongestionDataJob.region7);
        logger.info(LocalDateTime.now() + "拥堵信息：" + congestionInfo);
        return AjaxResult.success(congestionInfo);
    }

}
